import { defineStore } from 'pinia'
import { resetRouter } from '@/router'
import { useTagsStore, usePermissionStore } from '@/store'
import { removeToken, toLogin, type ResponseBody } from '@/utils'
import api from '@/api'

export const useUserStore = defineStore('user', {
  state() {
    return {
      userInfo: {} as Record<string, any>
    }
  },
  getters: {
    userId(): Key | undefined {
      return this.userInfo.id
    },
    name(): string | undefined {
      return this.userInfo.name
    },
    nickName(): string | undefined {
      return this.userInfo.nickName
    },
    avatar(): string | undefined {
      return this.userInfo.avatar
    },
    roles(): UserRoles {
      return this.userInfo.roles || []
    },
    permissions(): UserPermissions {
      return this.userInfo.permissions || []
    }
  },
  actions: {
    async getUserInfo() {
      try {
        const res = (await api.getUser()) as ResponseBody<TRecord<any>>
        this.userInfo = res.data || {}
        return Promise.resolve(res.data)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    async logout() {
      const { resetTags } = useTagsStore()
      const { resetPermission } = usePermissionStore()
      removeToken()
      resetTags()
      resetPermission()
      resetRouter()
      this.$reset()
      toLogin()
    },
    setUserInfo(userInfo = {}) {
      this.userInfo = { ...this.userInfo, ...userInfo }
    }
  }
})
